package ru.ifmo.ipimenov.ewf_svn.standalone.view.gui;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import ru.ifmo.ipimenov.ewf_svn.standalone.model.db.Document;
import ru.ifmo.ipimenov.ewf_svn.standalone.model.db.Rules;
import ru.ifmo.ipimenov.ewf_svn.standalone.model.list.RulesModel;
import ru.ifmo.ipimenov.ewf_svn.standalone.model.RulesProvider;
import ru.ifmo.ipimenov.ewf_svn.standalone.controller.AddRuleAction;
import ru.ifmo.ipimenov.ewf_svn.standalone.controller.RemoveRuleAction;

import javax.swing.*;
import java.awt.*;
import java.util.List;

/**
 * @author: Ilya Pimenov
 * Scartel Starlab company
 */
public class RuleForm extends JFrame {
    /**
     * Logger for all purposes
     */
    private static Log log = LogFactory.getLog(LoginForm.class);

    private Document d;

    private JButton removeButton;
    private JButton addButton;
    private JTextField text;

    private JList list;

    private Container contentPane;

    public RuleForm(Document d) {
        super("Rules management for " + d.getName());

        this.d = d;

        setPreferredSize(new Dimension(300, 200));
        int yLocation = (int)(Toolkit.getDefaultToolkit().getScreenSize().getHeight() / 2 - getPreferredSize().getHeight() / 2);
        int xLocation = (int)(Toolkit.getDefaultToolkit().getScreenSize().getWidth() / 2 - getPreferredSize().getWidth() / 2);
        setLocation(xLocation, yLocation);

        text = new JTextField("State2 Simple.test Up");        

        list = new JList();
        List<Rules> list2 = RulesProvider.getInstance().load(d);
        list.setModel(new RulesModel(list2));
        list.setSelectedIndex(0);

        removeButton = new JButton("Remove");
        removeButton.addActionListener(new RemoveRuleAction(list));

        addButton = new JButton("Add rule");
        addButton.addActionListener(new AddRuleAction(list, d, text));

        contentPane = getContentPane();
        addComponentsToPane();
    }

    private void addComponentsToPane() {
        JPanel p = new JPanel();
        p.setLayout(new BorderLayout(2, 2));
        p.add(removeButton, BorderLayout.WEST);
        p.add(addButton, BorderLayout.EAST);

        contentPane.setLayout(new BorderLayout(5, 5));

        if (!(contentPane.getLayout() instanceof BorderLayout)) {
            contentPane.add(new JLabel("Container doesn't use BorderLayout."));
            return;
        }

        contentPane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);

        list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        contentPane.add(new JScrollPane(list), BorderLayout.CENTER);
        contentPane.add(text, BorderLayout.PAGE_START);

        contentPane.add(p, BorderLayout.PAGE_END);
    }
}